package com.ruoyi.web.controller.api;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.shop.domain.*;
import com.ruoyi.shop.service.*;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.controller.api.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Api("C端商品相关接口")
@RestController
@RequestMapping("/shop")
public class TokenShopController {

    @Autowired
    private IUserAddressService userAddressService;
    @Autowired
    private IGoodsFollowService goodsFollowService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IOrdersService ordersService;
    @Autowired
    private IOrdersGoodsService ordersGoodsService;
    @Autowired
    private IUserGoodsSpecialService userGoodsSpecialService;
    @Autowired
    private IShopCartService shopCartService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private TokenService tokenService;


    @Log(title = "修改用户密码", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    @ApiOperation("修改用户密码")
    public R updatePwd(@RequestBody UserVo userVo)
    {
        String oldPassword =userVo.getOldPassword();
        String newPassword =userVo.getNewPassword();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password))
        {
            return R.fail("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password))
        {
            return R.fail("新密码不能与旧密码相同");
        }
        newPassword = SecurityUtils.encryptPassword(newPassword);
        if (userService.resetUserPwd(userId, newPassword) > 0)
        {
            // 更新缓存用户密码&密码最后更新时间
            loginUser.getUser().setPwdUpdateDate(DateUtils.getNowDate());
            loginUser.getUser().setPassword(newPassword);
            tokenService.setLoginUser(loginUser);
            return R.ok();
        }
        return R.fail("修改密码异常，请联系管理员");
    }


    @ApiOperation("获取订单详情")
    @GetMapping("/getOrderByOrderId")
    public R<OrdersVo> getOrderByOrderId(Long orderId) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        OrdersVo ordersVo = new OrdersVo();
        Orders orders = ordersService.selectOrdersById(orderId);
        ordersVo.setOrders(orders);
        OrdersGoods ordersGoods = new OrdersGoods();
        ordersGoods.setOrdersId(orderId);
        List<OrdersGoods> ordersGoodsList = ordersGoodsService.selectOrdersGoodsList(ordersGoods);
//        ordersGoodsList.forEach(item->{
//            Goods goods =goodsService.getdetails(item.getGoodsId(),loginUser.getUserId());
//            if(!Objects.isNull(goods) && !Objects.isNull(goods.getSpecial())){
//                item.setSpecial(goods.getSpecial());
//            }
//        });
        ordersVo.setOrdersGoods(ordersGoodsList);
        return R.ok(ordersVo);
    }

    @ApiOperation("查询商品是否在关注列表")
    @GetMapping("/checkGoodsFollow")
    public R<Boolean> checkGoodsFollow(Long goodsId) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        GoodsFollow goodsFollow = new GoodsFollow();
        goodsFollow.setUserId(loginUser.getUserId());
        goodsFollow.setGoodsId(goodsId);
        List<GoodsFollow> list = goodsFollowService.selectGoodsFollowList(goodsFollow);
        if (!list.isEmpty()){
            return R.ok(true);
        }
        return R.ok(false);
    }


    @ApiOperation("获取地址列表")
    @GetMapping("/getAddressList")
    public R<List<UserAddress>> getAddressList() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        UserAddress userAddress = new UserAddress();
        userAddress.setUserId(loginUser.getUserId());
        List<UserAddress> list = userAddressService.selectUserAddressList(userAddress);
        return R.ok(list);
    }

    @ApiOperation("修改地址")
    @PostMapping("editAddressList")
    @Transactional
    public R editAddressList(@RequestBody UserAddress userAddress) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        userAddress.setUserId(loginUser.getUserId());
        if(userAddress.getIsDefault().equals("Y")){
            //默认地址
            //先将所有地址设置为非默认
            userAddressService.editOtherAddress(userAddress);
        }

        userAddressService.updateUserAddress(userAddress);
        return R.ok();
    }

    @ApiOperation("新增地址")
    @PostMapping("/addAddressList")
    @Transactional
    public R addAddressList(@RequestBody UserAddress userAddress) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        userAddress.setUserId(loginUser.getUserId());
        if(userAddress.getIsDefault().equals("Y")){
            //默认地址
            //先将所有地址设置为非默认
            userAddressService.editOtherAddress(userAddress);
        }
        userAddressService.insertUserAddress(userAddress);

        return R.ok();
    }
    @ApiOperation("删除地址")
    @GetMapping("/delAddressList")
    public R<List<UserAddress>> getAddressList(Long addressId) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        UserAddress userAddress = new UserAddress();
        userAddress.setUserId(loginUser.getUserId());
        userAddress.setId(addressId);
        List<UserAddress> list = userAddressService.selectUserAddressList(userAddress);
        if (list.size() == 0) {
            return R.fail("地址不存在");
        }else{
            userAddressService.deleteUserAddressById(addressId);
        }
        return R.ok(list);
    }

    @ApiOperation("获取购物车信息")
    @GetMapping("/getCart")
    public R<List<ShopCart>> getCart() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        ShopCart shopCart = new ShopCart();
        shopCart.setUserId(loginUser.getUserId());
        List<ShopCart> shopCartList = shopCartService.selectShopCartList(shopCart);
        shopCartList.forEach(item -> {
            item.setGoods(goodsService.getdetails(item.getGoodsId(),loginUser.getUserId()));
        });
        return R.ok(shopCartList);
    }

    @ApiOperation("购买商品接口ActionSource=1 会删除购物车对应商品，0时不做处理")
    @PostMapping("/buy")
    @Transactional
    public R buy(@RequestBody BuyVo buyVo) {
        if (buyVo.getBuygoodVos().size() == 0) {
            return R.fail("订单商品数量为0，不能购买");
        }else{
            int num = 0;
            for (BuygoodVo buygoodVo : buyVo.getBuygoodVos()) {
                num+= (int) buygoodVo.getGoodsNum();
            }
            if (num == 0) {
                return R.fail("订单商品数量为0，不能购买");
            }
        }

        //判断商品库存
        for (BuygoodVo item : buyVo.getBuygoodVos()) {
            Goods goods= goodsService.selectGoodsById(item.getGoodsId());
            if(item.getGoodsNum()>goods.getInventory()){
                return R.fail("库存不足");
            }
        }



        LoginUser loginUser = SecurityUtils.getLoginUser();
        //创建订单0待付款 1待发货 2待收货 3已完成 4已取消
        Orders orders = new Orders();
        orders.setUserId(loginUser.getUserId());
        orders.setStatus("0");
        orders.setAddressName(buyVo.getAddressName());
        orders.setAddressTel(buyVo.getAddressTel());
        orders.setAddress(buyVo.getAddress());
        String originalString = loginUser.getUserId().toString();
        String paddedString = String.format("%05d", Integer.parseInt(originalString));
        orders.setOrderNo(UUIDOrderGenerator.generateOrderNo(paddedString));
        ordersService.insertOrders(orders);

        BigDecimal totalPrice = new BigDecimal(0);
        //如果该用户有特价商品应该计算特价商品
        for (BuygoodVo item : buyVo.getBuygoodVos()) {

            //查询商品信息
            Goods goods = goodsService.selectGoodsById(item.getGoodsId());
//            判断商品是否有特价
            UserGoodsSpecial userGoodsSpecial =  new UserGoodsSpecial();
            userGoodsSpecial.setUserId(loginUser.getUserId());
            userGoodsSpecial.setGoodsId(goods.getId());
            List<UserGoodsSpecial> specials = userGoodsSpecialService.selectUserGoodsSpecialList(userGoodsSpecial);
            BigDecimal price = goods.getPrice().multiply(new BigDecimal(item.getGoodsNum()));
            OrdersGoods ordersGoods = new OrdersGoods();
            if (specials.size() != 0) {
                price =specials.get(0).getSpecialPrice().multiply(new BigDecimal(item.getGoodsNum()));
                ordersGoods.setSpecial(specials.get(0).getSpecialPrice());
                ordersGoods.setGoodsAmountAll(specials.get(0).getSpecialPrice().multiply(BigDecimal.valueOf(item.getGoodsNum())));
            }else{
                ordersGoods.setGoodsAmountAll(goods.getPrice().multiply(BigDecimal.valueOf(item.getGoodsNum())));
            }

            totalPrice = totalPrice.add(price);
            //创建订单商品

            ordersGoods.setOrdersId(orders.getId());
            ordersGoods.setGoodsId(goods.getId());
            ordersGoods.setGoodsName(goods.getGoodName());
            ordersGoods.setGoodsNum(item.getGoodsNum());
            ordersGoods.setGoodsAmount(goods.getPrice());


            ordersGoods.setImages(goods.getBanners());
            ordersGoodsService.insertOrdersGoods(ordersGoods);


            if("1".equals(item.getActionSource())){
                //购物车
                //删除购物车商品
                ShopCart shopCart = new ShopCart();
                shopCart.setUserId(loginUser.getUserId());
                shopCart.setGoodsId(item.getGoodsId());
                shopCartService.delGoodsToCart(shopCart);
            }else{
                //但商品
            }
            //更新订单金额
            orders.setOrdersAmount(totalPrice);
            ordersService.updateOrders(orders);


        }


        return R.ok();
    }

    @ApiOperation("修改购物车商品数量")
    @PostMapping("/editGoodsToCart")
    public R editGoodsToCart(@RequestBody ShopCart shopCart) {
        //判断商品库存
        Goods goods= goodsService.selectGoodsById(shopCart.getGoodsId());
        if(shopCart.getGoodsNum()>goods.getInventory()){
            return R.fail("库存不足");
        }
        shopCartService.updateShopCart(shopCart);
        return R.ok();
    }

    @ApiOperation("购物车删除商品")
    @PostMapping("/delGoodsToCart")
    public R delGoodsToCart(@RequestBody List<ShopCart> shopCarts) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        shopCarts.forEach(item->{
            //判断购物车是否存在该商品
            ShopCart shopCart = new ShopCart();
            shopCart.setUserId(loginUser.getUserId());
            shopCart.setGoodsId(item.getGoodsId());
            shopCartService.delGoodsToCart(shopCart);
        });

        return R.ok();
    }

    @ApiOperation("商品加入购物车")
    @PostMapping("/addGoodsToCart")
    public R addGoodsToCart(@RequestBody ShopCart shopCart) {
        if (Objects.isNull(shopCart.getGoodsNum()) || shopCart.getGoodsNum() ==0) {
            return R.fail("商品数量不能为0");
        }

        LoginUser loginUser = SecurityUtils.getLoginUser();

        //判断购物车是否存在该商品
        ShopCart shopCart1 = new ShopCart();
        shopCart1.setUserId(loginUser.getUserId());
        shopCart1.setGoodsId(shopCart.getGoodsId());

        List<ShopCart> shopCartList = shopCartService.selectShopCartList(shopCart1);
        if(!shopCartList.isEmpty()){
            //判断商品库存
            Long num = shopCart.getGoodsNum()+shopCartList.get(0).getGoodsNum();
            Goods goods= goodsService.selectGoodsById(shopCart.getGoodsId());
            if(num>goods.getInventory()){
                return R.fail("库存不足");
            }
            //更新购物车
            shopCartList.get(0).setGoodsNum(num);
            shopCartService.updateShopCart(shopCartList.get(0));
        }else{

            //判断商品库存
            Goods goods= goodsService.selectGoodsById(shopCart.getGoodsId());
            if(shopCart.getGoodsNum()>goods.getInventory()){
                return R.fail("库存不足");
            }
            shopCart1.setGoodsNum(shopCart.getGoodsNum());
            //新增购物车
            shopCartService.insertShopCart(shopCart1);
        }
        return R.ok();
    }

    @ApiOperation("获取收藏商品列表")
    @GetMapping("/getFollowGoodsList")
    public R<List<Goods>> getFollowGoodsList() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<Goods> list =  goodsService.getFollowGoodsList(loginUser.getUserId());
        return R.ok(list);
    }

    @ApiOperation("收藏商品")
    @GetMapping("/followGoods")
    public R<List<Goods>> followGoods(Long goodsId) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        GoodsFollow goodsFollow = new GoodsFollow();
        goodsFollow.setUserId(loginUser.getUserId());
        goodsFollow.setGoodsId(goodsId);
        List<GoodsFollow> list = goodsFollowService.selectGoodsFollowList(goodsFollow);
        if (!list.isEmpty()) {
            return R.fail("已收藏该商品");
        }
        goodsFollowService.insertGoodsFollow(goodsFollow);
        return R.ok();
    }

    @ApiOperation("取消收藏商品")
    @GetMapping("/delFollowGoodsList")
    public R<List<Goods>> delFollowGoodsList(Long goodsId) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        GoodsFollow goodsFollow = new GoodsFollow();
        goodsFollow.setUserId(loginUser.getUserId());
        goodsFollow.setGoodsId(goodsId);
        List<GoodsFollow> list = goodsFollowService.selectGoodsFollowList(goodsFollow);
        if (!list.isEmpty()) {
            goodsFollowService.deleteGoodsFollowById(list.get(0).getId());
        }else{
            return R.fail("取消收藏失败");
        }
        return R.ok();
    }



    //    待付款	0
//    待发货	1
//    待收货	2
//    已完成	3
//    已取消	4
    @ApiOperation("获取订单列表 0待付款 1待发货 2待收货 3已完成 4已取消")
    @GetMapping("/getOrdersList")
    public R<List<OrdersVo>> getOrdersList(String orderStatus) {
        List<OrdersVo> ordersVoList = new ArrayList<>();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Orders orders = new Orders();
        orders.setUserId(loginUser.getUserId());
        if(orderStatus!=null && !"".equals(orderStatus)){
            orders.setStatus(orderStatus);
        }
        List<Orders> list =  ordersService.selectOrdersList(orders);

        list.forEach(item->{
            OrdersVo ordersVo = new OrdersVo();
            ordersVo.setOrders(item);
            OrdersGoods ordersGoods = new OrdersGoods();
            ordersGoods.setOrdersId(item.getId());
            List<OrdersGoods> list1 = ordersGoodsService.selectOrdersGoodsList(ordersGoods);
    //        list1.forEach(odrerGood ->{
            //    Goods goods =goodsService.getdetails(odrerGood.getGoodsId(),loginUser.getUserId());
//                if(!Objects.isNull(goods) && !Objects.isNull(goods.getSpecial())){
//                    odrerGood.setSpecial(goods.getSpecial());
//                }

//            });
            ordersVo.setOrdersGoods(list1);
            ordersVoList.add(ordersVo);
        });
        return R.ok(ordersVoList);
    }

    @ApiOperation("订单取消")
    @GetMapping("/cancelOrder")
    public R cancelOrder(String orderId) {
        ordersGoodsService.cancelOrder(orderId);
        return R.ok();
    }
}
